<?php
defined('BASEPATH') OR exit('No direct script access allowed');
header("Content-Type: text/html;charset=utf-8");

/**
 * Class Content
 */
class Content extends MY_Controller {
    
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
    }

    public function file()
    {
		
        $this->load->view('content/upload_form', array('error' => ' ' ));
    }
	  public function test()
    {
        $this->load->view('content/test');
    }
	
    /**
     * 文件处理
     */
    //请求样例:http://192.168.7.197:8090/?c=content&m=upload&merCode=602260&time=20180309131711&sign=9bcd0897bd3140016e68e9ee9316a4fa
    public function do_upload()
    {
          try{
            $this->load->library('Tool');
            $this->load->helper('func');
            $this->load->library('RedisHandle');
            $this->load->database();
            $params['merCode'] = $_GET['merCode'];
            $params['time'] = $_GET['time'];
            $params['sign'] = $_GET['sign'];
			
           // $params['key'] =$_GET['key'];
            $param['floder']= urldecode($_GET['floder']);
	//var_dump($_FILES);die;	
            //必填参数校验
            mustParams($params);
            $response = Tool::checkSign($params,$param['floder']);//签名验证
            if($response['code'] == 0){        
            //判断是否有分类
            if($param['floder']==''){
                $config['upload_path'] = FCPATH.'uploads/'.$params['merCode'];
				$path = '/uploads/'.$params['merCode'];
            }else{
                if(!file_exists( FCPATH.'uploads/'.$param['floder'])){
                    mkdir(FCPATH.'uploads/'.$param['floder'],0777,true);
                }
                $config['upload_path'] = FCPATH.'uploads/'.$param['floder'];
				$path = '/uploads/'.$param['floder'];

            }
             if(!file_exists($config['upload_path']))
            {
                mkdir($config['upload_path'],0777);
            }
            $config['allowed_types'] = 'gif|jpg|jpeg|png|zip';
            $config['max_size'] = '100000';
            $config['max_width'] = '1024';
            $config['max_height'] = '768';
	   // var_dump($config['allowed_types']);die;
            $this->load->library('upload', $config);
            //文件类型校验
            $type = explode('|',$config['allowed_types']);
            $str = $_FILES['file']['type'];
			if($str=="application/x-zip-compressed"){
				$subType = "zip";
            }else if($str =='application/zip'){
				$subType = "zip";
			}else if($str=='application/octet-stream'){
				$subType = 'ipk';
			}else if($str=='application/vnd.android.package-archive'){
				$subType='apk';
			}else{
				$subType = substr($str,strpos($str,'/')+1);
			}
            
	    //var_dump($subType);die;
            if(!in_array($subType,$type)){
                echo json_exit(10005,'文件类型错误');
            }          
            $this->upload->initialize($config);            
            if ($_FILES["file"]["error"] > 0) {
                echo  json_exit(10001,$_FILES["file"]["error"]);
			}else{
                if(file_exists(FCPATH.'uploads/'.$param['floder'].'/'.$_FILES['file']['name'])){
                    echo  json_exit(10002,$_FILES["file"]["name"].'文件已存在');           
                }
		
                $status = $this->upload->do_upload('file');
                if($status){
                    $fileId = date('YmdHis').mt_rand(1000, 9999);//文件存储id
                    $fileTime=date("Y-m-d H:i:s");//文件存储id
                    $fileMd5 = md5($fileId);
                    $fileName = $_FILES['file']['name'];//文件名
                    $fileSize = $_FILES['file']['size'];
                    	
                    if($param['floder']==''){
                         //带参数的请求url
                        $requestUrl = self::requestCdn.'&merCode='.$params['merCode'].'&vid='.$fileId;
                    }else{
                         $requestUrl = self::requestCdn.'&merCode='.$params['merCode'].'&vid='.$fileId.'&floder='.urlencode($param['floder']);
                    }
					$path = $path.'/'.$fileName;//数据库存储相对路径
					$creator = $params['merCode'];
					$a=filectime( $config['upload_path'] );//上一次修改时间					
					$modifytime = date("Y-m-d H:i:s",$a);
					
                        $data = array(
                        'vid' => $fileId,
                        'merCode'=> $params['merCode'],
                        'filename' => $fileName,
                        'time' => $fileTime,
                        'md5' =>$fileMd5,
                        'size'=>$fileSize,
						'floder'=>$param['floder'],
						'path'=> $path,
						'creator'=>$creator,
						'modifytime'=>$modifytime,
                          );
                    // 生成这样的SQL代码: INSERT INTO mytable (title, name, date) VALUES ('{$title}', '{$name}', '{$date}')                  
					$res= $this->db->insert('file_information', $data);               
                    $res = $this->db->affected_rows();
                    if($res){
                        $redis = RedisHandle::getInstance(); //存储$fileId
                        $key = RedisHandle::getKey($fileId);
                        $redis->set($key,$fileName);
						RedisHandle::close();
						$vid = $fileId;
						$muid = 123456;
						$merCode = $params['merCode'];
						$time = date('YmdHis');
						//$key = md5($time);
						$key = "032e71330511ad6aa3af0934662c9c35";
						$data = "merCode=".$merCode."&muid=".$muid."&vid=".$vid."&time=".$time."&0".$key;
						$sign = md5($data);
						echo json_exit(0,'ok',array('vid'=>$fileId,'md5'=>$fileMd5,'url'=>$requestUrl,'testUrl'=>$requestUrl.'&muid='.$muid.'&time='.$time.'&sign='.$sign));
                    }else{
                        echo json_encode(array('code'=>201,'message'=>"存储出错",'info'));
                    }                                   
                }else{
                    echo  json_exit(10001,$_FILES["file"]["error"]);
                }
            }
           }else{
                json_exit(10003,'签名不通过');
           }            
         }catch(Exception $e){
           json_exit(10006, $e->getMessage());         
        }     
    }
	
	/** php 接收流文件 
	* @param String $file 接收后保存的文件名 
	* @return boolean 
	*/
	 public function upload(){ 
	 $this->load->library('Tool');
        $this->load->helper('func');
        $this->load->library('RedisHandle');
        $this->load->database();
        $params['merCode'] = $_GET['merCode'];
        $params['time'] = $_GET['time'];
        $params['sign'] = $_GET['sign'];
        $param['floder']= urldecode($_GET['floder']);   
		$param['filename'] = $_GET['title'];	
		  
        mustParams($params);  //必填参数校验
	
        $response = Tool::checkSign($params,$param['floder']);//签名验证
		//var_dump($response);die();
        if($response['code'] == 0){
				//判断是否有分类
			if($param['floder']==''){
				if(!file_exists( FCPATH.'uploads/'.$params['merCode'])){
					mkdir( FCPATH.'uploads/'.$params['merCode'],0777);
				}
				$path = 'uploads/'.$params['merCode'];   
				 $floder = $params['merCode'];
			}else{
				if(!file_exists( FCPATH.'uploads/'.$param['floder'])){
					
					mkdir(FCPATH.'uploads/'.$param['floder'],0777,true);
				}
				$path = 'uploads/'.$param['floder']; 
				$floder = $param['floder'];
			}
			
			//文件流处理
			$streamData = isset($GLOBALS['HTTP_RAW_POST_DATA'])? $GLOBALS['HTTP_RAW_POST_DATA'] : ''; 
			if(empty($streamData)){ 
				$streamData = file_get_contents('php://input'); 
				// $json=json_decode($input,true); 
				// $base=base64_decode($json['info']); 			
			 } 
			 
			 $prev_name = date('YmdHis');
			 if($param['filename']!=''){
				
				$fileName = $param['filename'];
			}else{
				$fileName = $prev_name.'.zip';
			}
			$upload_path=FCPATH.$path.'/'.$fileName;
			$path = '/'.$path.'/'.$fileName;
			$a=filectime( upload_path );//上一次修改时间					
			$modifytime = date("Y-m-d H:i:s",$a);
			if($streamData!=''){ 				
				if(file_exists($upload_path)){
					echo json_exit(10002,'文件已存在');
				}
				//echo $receiveFile;die;
				$ret = file_put_contents($upload_path, $streamData, true);
				
			}else{ 
				json_exit(2000,"上传出错");
			} 
			$fileId =date('YmdHis').mt_rand(1000, 9999);//文件存储id
			
			$fileTime=date("Y-m-d H:i:s");
			$fileMd5 = md5($fileId);
			
			$creator = $params['merCode'];		
			if($param['floder']==''){
			   $requestUrl = self::requestCdn.'&merCode='.$params['merCode'].'&vid='.$fileId; //带参数的请求url
			}else{
			  $requestUrl = self::requestCdn.'&merCode='.$params['merCode'].'&vid='.$fileId.'&floder='.urlencode($param['floder']);
			}
			   $data = array(
					'vid' => $fileId,
					'merCode'=> $params['merCode'],
					'filename' => $fileName,
					'time' => $fileTime,
					'md5' => $fileMd5,
					'size' => $ret,
					'floder' => $floder,
					'path' => $path,
					'creator' => $creator,
					'modifytime'=>$modifytime,
					  );
				// 生成这样的SQL代码: INSERT INTO mytable (title, name, date) VALUES ('{$title}', '{$name}', '{$date}') 
			   $res= $this->db->insert('file_information', $data);
			   $res = $this->db->affected_rows();
			if(!empty($res)){
				$redis = RedisHandle::getInstance(); //存储$fileId
				$key = RedisHandle::getKey($fileId);
				$redis->set($key,$fileName);
				$vid = $fileId;
				$muid = 123456;
				$merCode = $params['merCode'];
				$time = date('YmdHis');
				//$key = md5($time);
				$key = "032e71330511ad6aa3af0934662c9c35";
				$data = "merCode=".$merCode."&muid=".$muid."&vid=".$vid."&time=".$time."&0".$key;
				$sign = md5($data);
				RedisHandle::close();
				echo json_exit(0,'ok',array('vid'=>$fileId,'md5'=>$fileMd5,'url'=>$requestUrl,'testUrl'=>$requestUrl.'&muid='.$muid.'&time='.$time.'&sign='.$sign));
			}else{
				 echo json_encode(array('code'=>201,'message'=>"存储出错",'info'));
			}		  
        }
	}

}
